<template>
    <div class="container">
        <el-card class="box-card">
            <div slot="header" class="clearfix">
                <span>商品详情</span>

            </div>
            <el-form ref="form" label-width="100px">
                <el-form-item label="商品id：">
                    <el-input v-model="id" disabled></el-input>
                </el-form-item>
                <el-form-item label="商品名称：">
                    <el-input v-model="name" placeholder="请输入内容"></el-input>
                </el-form-item>
                <el-form-item label="商品价格：">
                    <el-input-number v-model="price" :step="10" :min="10" :max="100"></el-input-number>
                </el-form-item>
                <el-button size="small" type="success" @click="editGoods">保存</el-button>
            </el-form>

            <el-upload ref="upload" class="upload-demo" action="`${process.env.VUE_APP_API_URL}/upload/uploadImage`"
                multiple accept="images/png" list-type="picture-card" drag :limit="10" :data="uploadData"
                :before-upload="beforeUpload" :on-progress="uploadProgress" :on-success="handleSuccess"
                :on-error="uploadError" :on-preview="handlePreview" :before-remove="beforeRemove" :on-remove="handleRemove"
                :on-exceed="handleExceed" :file-list="fileList">
                <el-button size="small" type="primary">点击上传</el-button>



            </el-upload>


            <div><el-divider>只能上传jpg/png文件，且不超过2MB</el-divider></div>
            <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>

        </el-card>

    </div>
</template>

<script>
export default {
    name: "uploadFile",
    data() {
        return {

            name: '',
            price: '',
            id: '',
            uploadData: {
                id: ''
            },
            fileList: [],
            dialogImageUrl: '',
            dialogVisible: false
        };
    },
    mounted() {
        const id = this.$route.params.id;
        this.selectById(id);
        console.log("id:" + id);
        this.uploadData.id = id;//商品id
        this.id = id
    },
    methods: {
        editGoods() {
            if (this.uploadData.id == '' && this.uploadData.id == null) {
                this.$message({
                    message: 'id不能为空',
                    type: 'error'
                })
                return;
            } else if (this.name == '' && this.name == null) {
                this.$message({
                    message: '名称不能为空',
                    type: 'error'
                })
                return;

            }
            this.$request.post('upload/editGoods', {
                id: this.id,
                name: this.name,
                price: this.price
            }).then((res) => {
                if (res.code === '200') {
                    this.$message({
                        message: res.data.message,
                        type: 'success'
                    })
                    this.selectById(this.id)
                }
            })
        },
        selectById(id) {
            this.$request.post('upload/selectGoods', {
                id: id
            }).then((res) => {
                this.id = id;
                this.name = res.data.name
                this.price = res.data.price;

                let imgList = res.data.imgList.list;
                if (imgList.length > 0) {
                    this.fileList = imgList[0].imageUrlList.map((item) => {
                        return {
                            name: item.imageName,
                            url: item.imageUrl,
                            id: item.imgId//新增
                        };
                    })
                }
            })
        },
        //图片上传成功之后：将上传图片的数据添加到fileList
        handleSuccess(response, file, fileList) {
            // 根据后端返回的数据修改fileList集合
            console.log("图片上传成功之后response:" + JSON.stringify(response));

            let uploadImg = response.data.map((item) => {
                return {
                    name: item.imageName,
                    url: item.imageUrl,
                    id: item.imgId,//新增
                    status: 'finished',
                };
            })
            console.log("###" + JSON.stringify(uploadImg));

            fileList.push(...uploadImg);

            // 更新fileList，触发重新渲染
            this.$forceUpdate();
        },

        //上传失败的逻辑
        uploadError(err, file, fileList) {
            this.$message({
                message: err.message,
                type: "error",
            });
        },
        saveGoods() {
            if (this.name == '') {
                this.$message({
                    message: "请输入商品名称",
                    type: "error",
                });
                return;
            }
            if (this.price == '') {
                this.$message({
                    message: "请输入商品价格",
                    type: "error",
                });
                return;
            }
            this.$request.post('upload/saveGoods', {

                name: this.name,
                price: this.price

            }).then((res) => {
                this.$message({
                    message: "保存成功",
                    type: "success",
                });
                this.uploadData.id = res.data;
            })

        },

        //点击上传成功之后的图片进行预览
        handlePreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },

        //上传之前调用：校验类型、大小
        beforeUpload(file) {
            if (this.uploadData.id == '') {
                this.$message({
                    message: "请先保存数据，再上传图片",
                    type: "error",
                });
                return false;
            }

            const fileSize = file.size / Math.pow(2, 20);
            if (file.type !== 'image/jpg' && file.type !== 'image/png') {
                this.$message.error('只能上传jpg/png文件')
                return false;
            }

            if (fileSize > 2) {
                this.$message.error("图片不能超过2MB")
                return false;
            }

            return true;
        },

        //删除之前的逻辑
        beforeRemove(file, fileList) {
            return this.$confirm(`确定要删除图片 ${file.name}吗？`);
        },

        //删除的逻辑
        handleRemove(file, fileList) {
            console.log("删除图片的file:" + JSON.stringify(file));
            if (this.id !== '') {
                //发送请求，删除商品的图片
                console.log("删除时的商品id:" + this.id);
                this.$request.post('upload/deleteGoodsImage?imgId=' + file.id, {
                    id: this.id,
                    imgId: file.id
                }).then((res) => {
                    this.$message({
                        message: "删除成功",
                        type: "success",
                    });
                    // 根据删除的文件信息修改fileList集合
                    const index = fileList.findIndex(item => item.id === file.id);
                    if (index !== -1) {
                        fileList.splice(index, 1);
                    }
                    // 返回true允许删除，返回false阻止删除
                    return true;
                })


            }

        },

        //文件超出个数限制时的钩子
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        },

        //上传时，执行的逻辑
        uploadProgress(event, file, fileList) {

        }
    },

}
</script>

<style>
.container {
    width: 1200px;
    margin: 0 auto;
}

.inputSize {
    width: 500px;
}
</style>